//JS的String.fromat函数
String.format = function() {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

//转换object对象为json字符串
String.getJsonString= function (jsonObj) {
         var sA = [];
         (function(o) {
             var isObj = true;
             if (o instanceof Array)
                 isObj = false;
             else if (typeof o != 'object') {
                 if (typeof o == 'string')
                     sA.push('"' + o + '"');
                 else
                     sA.push(o);
                 return;
             }
             sA.push(isObj ? "{" : "[");
             for (var i in o) {
                 if (o.hasOwnProperty(i) && i != 'prototype') {
                     if (isObj)
                         sA.push(i + ':');
                     arguments.callee(o[i]);
                     sA.push(',');
                 }
             }
             sA.push(isObj ? "}" : "]");
         })(jsonObj);
         return sA.slice(0).join('').replace(/,\}/g, '}').replace(/,\]/g, ']');
     }


//判断浏览器
function isIE() { //ie? 
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 1)
        return true;
    else
        return false;
}

//FF的innerText
if (!isIE()) { //firefox innerText define
    HTMLElement.prototype.__defineGetter__("innerText",
    function() {
        var anyString = "";
        var childS = this.childNodes;
        for (var i = 0; i < childS.length; i++) {
            if (childS[i].nodeType == 1)
            //anyString += childS[i].tagName=="BR" ? "\n" : childS[i].innerText;
                anyString += childS[i].innerText;
            else if (childS[i].nodeType == 3)
                anyString += childS[i].nodeValue;
        }
        return anyString;
    }
    );
    HTMLElement.prototype.__defineSetter__("innerText",
    function(sText) {
        this.textContent = sText;
    }
    );
}

//FF下的outerHTML
if (typeof (HTMLElement) != "undefined" && !window.opera) {
    HTMLElement.prototype.__defineGetter__("outerHTML", function() {
        var a = this.attributes, str = "<" + this.tagName, i = 0; for (; i < a.length; i++)
            if (a[i].specified)
            str += " " + a[i].name + '="' + a[i].value + '"';
        if (!this.canHaveChildren)
            return str + " />";
        return str + ">" + this.innerHTML + "</" + this.tagName + ">";
    });
    HTMLElement.prototype.__defineSetter__("outerHTML", function(s) {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var df = r.createContextualFragment(s);
        this.parentNode.replaceChild(df, this);
        return s;
    });
    HTMLElement.prototype.__defineGetter__("canHaveChildren", function() {
        return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
    });
}

//自定义的Trim函数
String.prototype.Trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function() {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function() {
    return this.replace(/(\s*$)/g, "");
}


//日期转换成yyyy-MM-dd格式的字符串
function DateToString(date) {
    if (date != "") {
        var vMonth = date.getMonth() + 1;
        var vDate = date.getDate();
        return date.getFullYear() + "-" + (vMonth < 10 ? ("0" + vMonth) : vMonth)
        + "-" + (vDate < 10 ? ("0" + vDate) : vDate);
    }

    return date;
}

//日期转换成MM/dd/yyyy格式的字符串
function DateToStringUS(date) {
    if (date != "") {
        var vMonth = date.getMonth() + 1;
        var vDate = date.getDate();
        return (vMonth < 10 ? ("0" + vMonth) : vMonth)
        + "/" + (vDate < 10 ? ("0" + vDate) : vDate) + "/" + date.getFullYear();
    }

    return date;
}

//yyyy-MM-dd格式字符串转日期
function StringToDate(dateString) {
    var tmp = dateString.split("-");
    return new Date(tmp[0], eval(tmp[1]) - 1, tmp[2]);
}

//MM/dd/yyyy格式字符串转日期
function StringToDateUS(dateString) {
    var tmp = dateString.split("/");
    return new Date(tmp[2], eval(tmp[0]) - 1, tmp[1]);
}

//按字符串格式转日期,tiya,add
function StringToDateByFormat(dateString, format) {
    var splitter = "-";
    if (format.indexOf("/") > 0)
        splitter = "/";

    var tmpFormat = format.split(splitter);
    var arr = new Array(3);
    var firstChar;

    for (i = 0; i < 3; i++) {
        firstChar = tmpFormat[i].substring(0, 1);
        switch (firstChar) {
            case "y":
                arr[0] = i;
                break;
            case "M":
                arr[1] = i;
                break;
            case "d":
                arr[2] = i;
                break;
        }
    }

    var tmp = dateString.split(splitter);
    return new Date((tmp[arr[0]].length == 2 ? "20" + tmp[arr[0]] : tmp[arr[0]]), eval(tmp[arr[1]]) - 1, tmp[arr[2]]);
}

//日期计算  
Date.prototype.DateAdd = function(strInterval, Number) {
    var dtTmp = this;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}

//计算日期偏差，toDate-fromDate，tiya,add
function GetDayDiff(fromDate, toDate) {

    var day = 1000 * 60 * 60 * 24;
    var diff = Math.ceil((toDate - fromDate) / day);
    return diff;
}

function AppendRowsWithHTML(table, htmlContent) {
    var p = table.outerHTML.lastIndexOf("</TBODY>");
    var TableDiv = document.getElementById("<%=DataGrid.ClientID %>");
    TableDiv.innerHTML = table.outerHTML.substr(0, p) + String.format(NewRowHtml, UnSaveDraftsCount - 1, "") + table.outerHTML.substr(p);
    table = document.getElementById("EvaluationPeriodTable");
    for (var i = 1; i < table.rows.length; i++) {
        table.rows[i].cells[0].onclick = function() {
            EditCell(this);
        };
    }
}

function getScrollTop() {
    var scrollTop = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    return scrollTop;
}

function getScrollLeft() {
    var scrollLeft = 0;
    if (document.documentElement && document.documentElement.scrollLeft) {
        scrollLeft = document.documentElement.scrollLeft;
    }
    else if (document.body) {
        scrollLeft = document.body.scrollLeft;
    }
    return scrollLeft;
}


//host,请修改为实际部署的站点url，不要以"/"结尾u
var host = "";  //http://scoatest02/EDS
//MsgBox 第一个是内容，第二个是标题。第三个是类型，一般为null，第四个是确定执行的命令，第五个是传入的数据，第六个是取消执行的命令。
var MsgBoxPara = null;
function MsgBox(prompt, title, type, returnFunction, obj, cancelFunction) {
   
    if (cancelFunction == undefined) {
        cancelFunction = "";
    }
    MsgBoxPara = null;
    MsgBoxPara = {
        MsgBoxType: type,
        MsgBoxPrompt: prompt,
        MsgBoxTitle: title,
        MsgBoxReturnFunction: returnFunction,
        MsgBoxCancelFunction: cancelFunction,
        MsgBoxObj: obj
    }
    jQuery.facebox({ ajax: '/QualityManagementTool/Popup/popup.html' });
}

//MsgBoxEX,tiya add,p_MsgboxEx.aspx,可设置cancel和ok按钮的title值和弹出div的宽度
var MsgBoxExPara = null;
function MsgBoxEx(prompt, title, type, returnFunction, obj, cancelFunction, cancelTitle, oKTitle, boxDivWidth) {

    if (cancelFunction == undefined) {
        cancelFunction = "";
    }
    MsgBoxExPara = null;
    MsgBoxExPara = {
        MsgBoxType: type,
        MsgBoxPrompt: prompt,
        MsgBoxTitle: title,
        ButtonCancelTitle: cancelTitle,
        ButtonOKTitle: oKTitle,
        MsgBoxDivWidth: boxDivWidth,
        MsgBoxReturnFunction: returnFunction,
        MsgBoxCancelFunction: cancelFunction,
        MsgBoxObj: obj
    }
    jQuery.facebox({ ajax: host + '/Popup/p_MsgboxEx.aspx' });
}


function openWindowWithPost(url, name, keys, values) {
    var newWindow = window.open(url, name, "top=6000, left=6000,height=1,width=1,status=no,toolbar=no,menubar=no,location=no");
    if (!newWindow) return false;
    var html = "";
    html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
    if (keys && values && (keys.length == values.length))
        for (var i = 0; i < keys.length; i++)
        html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
    html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</script></body></html>";
    newWindow.document.write(html);
    return newWindow;
}


function QueryString(sName) {
    var sSource = String(window.document.location); //链接路径
    var sReturn = "";
    var sQUS = "?";
    var sAMP = "&";
    var sEQ = "=";
    var iPos;
    //记下(?)的位置
    iPos = sSource.indexOf(sQUS);
    if (iPos != -1) {
        //记下参数据串
        var strQuery = sSource.substr(iPos, sSource.length - iPos);
        //变为小写字母
        var strLCQuery = strQuery.toLowerCase();
        //sName:输入的参数名称
        var strLCName = sName.toLowerCase();

        iPos = strLCQuery.indexOf(sQUS + strLCName + sEQ); //?+sName+=
        if (iPos == -1)//如果第一个位置不是所求参数，则判断&+sName+=
        {
            iPos = strLCQuery.indexOf(sAMP + strLCName + sEQ); //&+sName+=
            if (iPos == -1)//如果不存在则返回空
                return "";
        }
        //返回存在的位置
        sReturn = strQuery.substr(iPos + sName.length + 2, strQuery.length - (iPos + sName.length + 2));
        //返回下一个&位置
        var iPosAMP = sReturn.indexOf(sAMP);
        if (iPosAMP == -1)
            return sReturn; //返回空
        else {
            sReturn = sReturn.substr(0, iPosAMP);
        }
    }
    else
        sReturn = "";
    return sReturn;
}

String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function(m, i) {
            return args[i];
        });
    }

    //编辑日期
    function SetDate(o, callback) {

        var txtDate = $(o);
        var oldDate;
        if (txtDate.val() != "") {
            oldDate = StringToDateUS(txtDate.val());
        }
        else {
            oldDate = new Date();
        }
        if (typeof (callback) == "undefined") {
            txtDate.attr("DeelSelectDate", "EndEditDate");
        }
        else {
            txtDate.attr("DeelSelectDate", callback);
        }
        setday(txtDate.get(0), oldDate);
    }

    //结束编辑日期
    function EndEditDate(textbox) {
        var txt = $(textbox);
        txt.val(DateToStringUS(txt.attr("NewDate")));
    }

    //客户端输入限制
    function regInput(obj, reg, inputStr, inputKey) {
        var str = "";
        if (isIE()) {
            if (inputStr == null) {
                inputStr = String.fromCharCode(inputKey);
            }
            var docSel = document.selection.createRange();
            oSel = docSel.duplicate();
            oSel.text = "";
            var srcRange = obj.createTextRange();
            oSel.setEndPoint("StartToStart", srcRange);
            var str = oSel.text + inputStr + srcRange.text.substr(oSel.text.length);
        }
        else {
            if (inputStr == null) {
                if (inputKey == 8 || inputKey == 0) {
                    return true;
                }
                var inputStr = String.fromCharCode(inputKey);
            }
            if (obj.selectionStart != undefined) {
                str = obj.value.substring(0, obj.selectionStart) + inputStr + obj.value.substring(obj.selectionEnd);
            }
        }       

        
        if (reg == "No Quotation") {
            reg = /^[^,'"]*$/;
        }
        if (reg == "Positive Integer") {
            reg = /^[1-9]\d*$/;
        }
        if (reg == "Nonnegative Integer") {
            reg = /^(([1-9]\d*)|0)$/;
        }
        if (reg == "Nonnegative 1 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,1})?|0\.?|0\.\d{0,1})$/;
        }
        if (reg == "Nonnegative 2 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,2})?|0\.?|0\.\d{0,2})$/;
        }

        if (reg == "Nonnegative 3 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,3})?|0\.?|0\.\d{0,3})$/;
        }

        if (reg == "Nonnegative 4 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,4})?|0\.?|0\.\d{0,4})$/;
        }

        if (reg == "Nonnegative 5 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,5})?|0\.?|0\.\d{0,5})$/;
        }

        if (reg == "Nonnegative 6 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,6})?|0\.?|0\.\d{0,6})$/;
        }
        if (reg == "Nonnegative 7 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,7})?|0\.?|0\.\d{0,7})$/;
        }
        if (reg == "Nonnegative 8 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,8})?|0\.?|0\.\d{0,8})$/;
        }
        if (reg == "Nonnegative 9 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,9})?|0\.?|0\.\d{0,9})$/;
        }
        
        if (reg == "Nonnegative 10 Bit Decimal") {
            reg = /^([1-9]\d*(\.\d{0,10})?|0\.?|0\.\d{0,10})$/;
        }

        

        return reg.test(str);
    }

    function CheckLimit(input, minValue, maxValue, allownull) {      

        if (input.length == 0) {
            if (allownull == undefined || allownull.toLowerCase() == 'true') {
                return input;
            }
            else {
                return minValue;
            }
        }

        if (maxValue != undefined && parseFloat(input) > parseFloat(maxValue)) {
            return maxValue;
        }

        if (minValue != undefined && parseFloat(input) < parseFloat(minValue)) {
            return minValue;
        }

        return parseFloat(input);
    }

    //网站基础URLBase
    var AjaxActionNow = false;


    /*  add by zed 2010-10-19  控制pagerBar分页显示 稍后再修改  */

    // totalcount:数据总数  ，currentindex:当前页  ,pageSize：每页数量   containerSelector：pageBar所在容器的JQ选择符字符串（eg: "#id",".class"） , SearchFnName:搜索方法名
    function bindPageBar(totalcount, currentindex, pageSize, containerSelector, SearchFnName, Params) {
        //strParams = strParams || "x";
        $(containerSelector + "  .pageNum li:not(.next,.last,.prev,.first) ").remove();
        var lilist = $(containerSelector + "  .pageNum li");
        var pagesize = pageSize;  //$(".resultsPerPage .selectBoxInput input").val();
        var totalpage = totalcount % pagesize != 0 ? ~ ~(totalcount / pagesize + 1) : totalcount / pagesize;
        totalpage = totalpage || 1;
        var linext = lilist.filter(".next");
        var lilast = lilist.filter(".last");
        var liprev = lilist.filter(" .prev");
        var lifirst = lilist.filter(".first");
        var pageBarBtCount = 5;

        lilist.children("a").removeClass("disable");
        lilist.unbind("click");
        // li: first prev next last current  pageBar:pageNum
        if (totalpage == 1) {
            lilist.children("a").addClass("disable");
            liprev.after("<li class=\"current\"><a  href=\"javascript:void(0);\">1</a></li>");
            return;
            //lilist.append
        } else {

        var start = end = 0;
        if (totalpage <= pageBarBtCount) {
            start = 1;
            end = totalpage;
            }
            else if (totalpage > pageBarBtCount && currentindex - 2 <= 0) { //大于5页时，并且当前页在开始2页
            start = 1;
            end = pageBarBtCount;
            }
            else if (totalpage > pageBarBtCount && currentindex + 2 >= totalpage) { //大于5页时，当前页在最后两页
            start = totalpage - pageBarBtCount + 1;
            end = totalpage;
            }
            else {
                start = currentindex - 2;
                end = currentindex + 2;
            }
            /// v
            var _list = [];
            for (var i = start; i <= end; i++) {
                var _li = $("<li ><a  href=\"javascript:void(0);\">" + i + "</a></li>");
                if (i == currentindex)
                    _li.addClass("current");
                else
                    _li.bind("click", [i, SearchFnName, Params], pageBarSearch);
                _list.push(_li);
            }
            $.each(_list, function(i, o) {
                linext.before(o);
            })
            
        }



        //设置按钮状态
        if (currentindex == 1 && totalpage == currentindex) {
            liprev.children("a").addClass("disable");
            lifirst.children("a").addClass("disable");
            lilast.children("a").addClass("disable");
            linext.children("a").addClass("disable");
        }
        else if (currentindex == 1) {
            liprev.children("a").addClass("disable");
            lifirst.children("a").addClass("disable");

            lilast.bind("click", [totalpage, SearchFnName, Params], pageBarSearch);
            linext.bind("click", [currentindex + 1, SearchFnName, Params], pageBarSearch);
        }
        else if (currentindex == totalpage) {
            lilast.children("a").addClass("disable");
            linext.children("a").addClass("disable");

            lifirst.bind("click", [1, SearchFnName, Params], pageBarSearch);
            liprev.bind("click", [currentindex - 1, SearchFnName, Params], pageBarSearch);
        }
        else if (currentindex != totalpage) {
            lilast.bind("click", [totalpage, SearchFnName, Params], pageBarSearch);
            linext.bind("click", [currentindex + 1, SearchFnName, Params], pageBarSearch);
            lifirst.bind("click", [1, SearchFnName, Params], pageBarSearch);
            liprev.bind("click", [currentindex - 1, SearchFnName, Params], pageBarSearch);
        }
    }

    function pageBarSearch(parm, FnName, Params) {
        if ((typeof parm).toLowerCase() == "object") {
            FnName = parm.data[1];
            Params = parm.data[2];
            parm = parm.data[0];
        }
        var fn = new Function("return " + FnName + ";")();
        fn([parm, Params]);
    }


    function ForDight(Dight, How) {
        Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
        return Dight;
    }

    function UpdateSelect(selector, values, selectValue) {
        var parentObj = $(selector);
        parentObj.find("option").each(function() { $(this).remove(); });
        var select = parentObj.find("select");
        if (values != null && values.length > 0) {

            for (var i = 0; i < values.length; i++) {
                var m = values[i];

                var selected = "";
                if (selectValue != undefined && selectValue.Trim().toLowerCase() == m.Value.Trim().toLowerCase()) {
                    selected = "selected";
                }

                select.append("<option " + selected + " value='" + m.Value + "'>" + m.Text + "</option>");
            }
        }

        parentObj.children().each(function() { $(this).remove(); });
        parentObj.append(select);

        FormWidget.dft(selector)
    }

